package com.sanchunhui.psc.ui.activity

import android.os.Bundle
import android.text.Editable
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.j256.ormlite.android.AndroidDatabaseConnection
import com.kotlin.provider.router.RouterPath
import com.sanchuihui.presenter.view.LoginView
import com.sanchunhui.psc.R
import com.sanchunhui.psc.common.BaseApplication
import com.sanchunhui.psc.common.BaseConstant
import com.sanchunhui.psc.data.dao.PSCOpenHelper
import com.sanchunhui.psc.data.protocol.ResponseInfo
import com.sanchunhui.psc.data.protocol.UserInfo
import com.sanchunhui.psc.ext.enable
import com.sanchunhui.psc.ext.onClick
import com.sanchunhui.psc.injection.component.DaggerUserComponent
import com.sanchunhui.psc.injection.module.UserModule
import com.sanchunhui.psc.presenter.LoginPresenter
import com.sanchunhui.psc.utils.GlideUtils
import com.sanchunhui.ui.activity.BaseMvpActivity
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_login.mUserIconIv
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.sql.Savepoint

/**
 * @Author zyx
 * @Date 2021/4/15-17:34
 * @Dscribe
 */
@Route(path = RouterPath.UserCenter.PATH_LOGIN)
class LoginActivity :  BaseMvpActivity<LoginPresenter>(), LoginView, View.OnClickListener {

//    @Autowired(name = RouterPath.MessageCenter.PATH_MESSAGE_PUSH)
//    @JvmField
//    var mPushProvider:PushProvider? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        initView()
        initData()
    }

    /*
        初始化视图
     */
    private fun initView() {
        mLoginBtn.enable(mMobileEt,{isBtnEnable()})
        mLoginBtn.enable(mPwdEt,{isBtnEnable()})
        mLoginBtn.onClick(this)
    }

    /*
        初始化数据
     */
    private fun  initData() {
        val user = BaseApplication.mUser
        if (user.phone != null) {
            mMobileEt.text = Editable.Factory.getInstance().newEditable(user.phone.toString())
        }
        GlideUtils.loadUrlImage(this, BaseConstant.IMAGE_SERVER_ADDRESS_URL+"${user.id%1000}/${user.id}.jpg",mUserIconIv)
    }

    /*
        Dagger注册
     */
    override fun injectComponent() {
        DaggerUserComponent.builder().activityComponent(mActivityComponent).userModule(UserModule()).build().inject(this)
        mPresenter.mView = this
    }

    /*
        点击事件
     */
    override fun onClick(view: View) {
        when(view.id){
//            R.id.mRightTv -> {startActivity<RegisterActivity>()}
            R.id.mLoginBtn -> {
                mPresenter.login(mMobileEt.text.toString(),mPwdEt.text.toString())
            }
//            R.id.mForgetPwdTv ->{
//                startActivity<ForgetPwdActivity>()
//            }
        }
    }

    /*
       判断按钮是否可用
    */
    private fun isBtnEnable():Boolean{
        return mMobileEt.text.isNullOrEmpty().not() &&
                mPwdEt.text.isNullOrEmpty().not()
    }

    /*
        登录回调
     */
    override fun onLoginResult(result: ResponseInfo) {
        if (result.code == 0) {
            val json = result.data
            parserJson(json.toString(),result.token)
        } else if (result.code == 400) {
            toast("密码不正确")
        }
    }

    fun parserJson(json: String, token:String?) {
        var user = Gson().fromJson(json, UserInfo::class.java)
        user.token = token
        user.loginId = user.id
        if (user != null) {
            // 缓存到内存中
            BaseApplication.mUser = user
            var connection: AndroidDatabaseConnection? = null
            var startPoint: Savepoint? = null
            try {
                // 缓存到本地数据库中，SqliteOpenhelper,要使用SQL语句
                //第三方ORM框架(ormLite，greendao),直接提交javabean
                val pscOpenHelper = PSCOpenHelper(this)
                val userDao = pscOpenHelper.getDao(UserInfo::class.java)
                //保证如果已有此用户，就不需要创建了
//            userDao.create(user)
//            userDao.createOrUpdate(user)
//            Log.e("login","创建新用户或者更新老用户信息")
                connection =
                    AndroidDatabaseConnection(pscOpenHelper.writableDatabase, true)
                startPoint = connection.setSavePoint("start")
                connection.isAutoCommit = false // 取消自动提交
                //TODO:区分新用户和老用户，并且统计比率
                val userList: List<UserInfo> = userDao.queryForAll()
                var isOldUser : Boolean = false
                for (i in 0 until userList.size) {
                    val u = userList.get(i)
                    if (u.id == user.id) {
                        isOldUser = true
                    }
                }
                if (isOldUser) {
                    userDao.update(user)
                    Log.e("login", "老用户更新信息")
                } else {
                    userDao.create(user)
                    Log.e("login", "新用户登录")
                }
                connection.commit(startPoint) // 提交事务
                Log.e("login","事务正常")
            }catch (e:Exception) {
                Log.e("login","出现ormlite事务异常"+e.localizedMessage)
                onLoginFailed()
                if (connection != null) {
                    connection.rollback(startPoint)
                }
            }
            onLoginSuccess()
        } else {
            onLoginFailed()
        }
    }

    override fun onError(text: String) {
        super.onError(text)
        toast(text)
    }

    fun onLoginSuccess() {
        val toast = Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT)
        toast.setGravity(Gravity.CENTER, 0, 0)
        toast.show()
        startActivity<MainActivity>()
        finish()

    }

    fun onLoginFailed() {
        val toast = Toast.makeText(this, "连接服务失败", Toast.LENGTH_SHORT)
        toast.setGravity(Gravity.CENTER, 0, 0)
        toast.show()
    }
}